import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/',
    name: 'layout',
    component: () => import('../views/layout/Layout.vue'),
    redirect: '/home', // 默认重定向到首页
    meta: { requiresAuth: true }, // 需要登录才能访问
    children: [
      { path: 'home', name: 'home', component: () => import('../views/home/index.vue') },
      { path: 'clue/list', name: 'clue-list', component: () => import('../views/clue/list.vue') },
      { path: 'clue/pool', name: 'clue-pool', component: () => import('../views/clue/pool.vue') },
      { path: 'business/list', name: 'business-list', component: () => import('../views/business/list.vue') },
      { path: 'business/add', name: 'business-add', component: () => import('../views/business/add.vue') },
      { path: 'business/pool', name: 'business-pool', component: () => import('../views/business/pool.vue') },
      { path: 'business/detail/:id', name: 'business-detail', component: () => import('../views/business/detail.vue') },
      { path: 'customer', name: 'customer', component: () => import('../views/customer/index.vue') },
      { path: 'resource/course', name: 'resource-course', component: () => import('../views/resource/course.vue') },
      { path: 'resource/activity', name: 'resource-activity', component: () => import('../views/resource/activity.vue') },
      { path: 'system/dept', name: 'system-dept', component: () => import('../views/system/dept.vue') },
      { path: 'system/role', name: 'system-role', component: () => import('../views/system/role.vue') },
      { path: 'system/user', name: 'system-user', component: () => import('../views/system/user.vue') },
      { path: 'system/log', name: 'system-log', component: () => import('../views/system/log.vue') }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/login/index.vue')
  },
  // 默认重定向到登录页
  {
    path: '/:pathMatch(.*)*',
    redirect: '/login'
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 检查是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 获取token
    const token = localStorage.getItem('token')
    // 如果没有token，重定向到登录页
    if (!token) {
      ElMessage.warning('请先登录')
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 保存当前路径，登录后可以重定向回来
      })
    } else {
      next() // 有token，继续访问
    }
  } else {
    next() // 不需要认证的页面，直接访问
  }
})

export default router
